import React, {
    useEffect,
    useState,
} from "react";
import {
    useDispatch
} from "react-redux";
import axiosMethod from "../util/axios";
import { Spin } from "antd";
import { getQueryVariable } from "../util";
import CONFIG from "../util/config";
import { Redirect, Route, Switch } from 'react-router-dom'
import { Routers } from '../routers/index'
import {SKIN_BG_COLOR} from '../hooks/useGetThem'
import "./app.scss";


const {
    appAddr,
} = CONFIG;



function App(props) {
    const [init, setInit] = useState(false);
    const [skin, setSkin] = useState('s2')
    const [moduleInfo, setModuleInfo] = useState([])
    const dispatch = useDispatch();

    const getCommonData = () => {
        //获取系统信息
        axiosMethod({
            type: "get",
            url: "/api/commons/users/info",
            body: {
                token: getQueryVariable('lg_tk')
            },
            showError: false,
            callback: function (res) {
                let isEdu = false
                if (res.eduId) {
                    dispatch({
                        type: 'SET_ISEDU',
                        data: true
                    })
                    isEdu = true
                    res.schoolId = res.eduId
                }
                if (!isEdu) {
                    //网站信息
                    axiosMethod({
                        type: "get",
                        url: "/api/commons/system/getServerInfo",
                        body: {
                            sysIds: 262
                        },
                        callback: function (res) {
                            dispatch({
                                type: 'SET_NOTICEADDR',
                                data: res[0].webSvrAddr
                            })
                        }
                    });
                }

                let currentIdentityList = res.userIdentityList
                if (currentIdentityList && Array.isArray(currentIdentityList)) {
                    let newArr = currentIdentityList.filter((item) => {
                        return item.identityCode == getQueryVariable('lg_ic')
                    })

                    if (newArr?.length) {
                        sessionStorage.setItem('currentIdentity', JSON.stringify(newArr[0]))
                        dispatch({
                            type: 'SET_CURRENTIDENTITY',
                            data: newArr[0]
                        })
                    } else {
                        sessionStorage.setItem('currentIdentity', JSON.stringify(currentIdentityList[0]))
                        dispatch({
                            type: 'SET_CURRENTIDENTITY',
                            data: currentIdentityList[0]
                        })
                    }

                }

                axiosMethod({
                    type: 'get',
                    url: 'api/commons/system/getServerInfo',
                    body: {
                        sysIds: '000'
                    },
                    callback: function (data) {
                        dispatch({
                            type: 'SET_MAINSERVER',
                            data: data[0].webSvrAddr
                        })
                        sessionStorage.setItem('baseUrl', data[0].webSvrAddr)
                        let messageId = '210'
                        if (isEdu) {
                            messageId = '211'
                        }

                        // 获取皮肤值
                        axiosMethod({
                            url: data[0].webSvrAddr + 'openapi/v1/system/facade/getSkin',
                            body: {
                                appid: messageId,
                                token: getQueryVariable('lg_tk'),
                            },
                            showError:false, callback: (skinResult) => {
                                const { skin: skinInfo = '2' } = skinResult
                                dispatch({
                                    type: 'SET_SKIN',
                                    data: `s${skinInfo}`
                                })
                                sessionStorage.setItem('skin', skinInfo)
                                setSkin(skinInfo)
                            }
                        })
        

                        if (!isEdu) {
                            // 获取基础信息
                            axiosMethod({
                                url: '/api/commons/schools/school/details',
                                body: {
                                    eduId: res.schoolId
                                },
                                showError: false,
                                callback: function (response) {
                                    let userInfo = res || {}
                                    userInfo['SchoolID'] = res.schoolId
                                    userInfo['SchoolLevel'] = response?.schoolLevel || 2
                                    userInfo['SchoolType'] = response?.schoolType || ''
                                    userInfo['UserID'] = userInfo.userId
                                    userInfo['UserType'] = userInfo.userType
                                    userInfo['UserName'] = userInfo.userName
                                    userInfo['PhotoPath'] = userInfo.photoPath

                                    dispatch({
                                        type: 'SET_SYSINFO',
                                        data: response
                                    })


                                    if (isEdu) {
                                        userInfo.SchoolID = res.schoolId
                                    } else if (!userInfo.SchoolID && !userInfo.eduId) {
                                        userInfo.SchoolID = getQueryVariable('schoolId') ? getQueryVariable('schoolId') : sessionStorage.getItem('schoolId')
                                    }

                                    axiosMethod({
                                        url: 'api/commons/schools//current/term?schoolId=' + userInfo.SchoolID,
                                        data: {
                                            eduId: userInfo.SchoolID
                                        },
                                        callback: (res) => {
                                            userInfo['termStartDate'] = res.termStartDate
                                            userInfo['termEndDate'] = res.termEndDate
                                            dispatch({ type: 'SET_USERINFO', data: userInfo })
                                            setInit(true)
                                            sessionStorage.setItem('userInfo', JSON.stringify(userInfo))

                                        }
                                    })
                                }
                            })
                        }else{
                            let userInfo = res || {}
                            userInfo['SchoolID'] = res.schoolId
                            userInfo['SchoolLevel'] = '3'
                            userInfo['UserID'] = userInfo.userId
                            userInfo['UserType'] = userInfo.userType
                            userInfo['UserName'] = userInfo.userName
                            userInfo['PhotoPath'] = userInfo.photoPath
                            dispatch({
                                type: 'SET_SYSINFO',
                                data: {
                                    schoolLevel:'3'
                                }
                            })

                            dispatch({ type: 'SET_USERINFO', data: userInfo })
                            // debugger
                            setInit(true)
                            sessionStorage.setItem('userInfo', JSON.stringify(userInfo))
                        }

                        if (!getQueryVariable("lg_tk")) {
                            window.location.href = data[0].webSvrAddr + `/UserMgr/Login/Login.aspx?lg_sysid=${messageId}&lg_preurl=${encodeURIComponent(appAddr)}`;
                            return;
                        }
                        let token = getQueryVariable("lg_tk");
                        sessionStorage.setItem("token", token);
                        // let script = document.createElement("script");
                        // script.src = data[0].webSvrAddr + "/UserMgr/Login/JS/CheckIsOnline2.js";
                        // script.type = "text/javascript";
                        // script.onload = function () {
                        //     window._LgBase_initCheck(data[0].webSvrAddr, token, messageId);
                        // }
                        // document.getElementsByTagName("head")[0].appendChild(script);

                        let count =0
                         //做掉线检测
                         if (count) {
                            return;
                        }
                        let script = document.createElement("script");
                        script.src = data[0].webSvrAddr + "/UserMgr/Login/JS/CheckIsOnline2.js";
                        script.type = "text/javascript";
                        script.onload = function () {
                            window._LgBase_initCheck(data[0].webSvrAddr, token, messageId);
                        }
                        document.getElementsByTagName("head")[0].appendChild(script);
                        count++;
                    }
                })
            }
        })
    }

    useEffect(() => {
        // setInit(true);
        sessionStorage.setItem('token', getQueryVariable('lg_tk'))
        getCommonData();
    }, []);
    useEffect(() => {
        // 根据 skin 的值向 <body> 元素添加或移除类名
        if (skin) {
            document.body.classList.add(`lg-skin-s${skin}`);
        }
    }, [skin])
    if (!init) {
        return <Spin className="app_load" spinning={true} tip="加载中..." />
    }
    return (
        <div className={`root`} style={{
            backgroundColor:SKIN_BG_COLOR[`s${skin}`]
        }}>
            <Switch>
                {
                    Routers.map(router => (
                        <Route
                            exact={!router.notExect}
                            key={router.path}
                            path={router.path}
                            component={router.component}
                        >
                        </Route>
                    ))
                }
                <Redirect path="/" to="/index" />
            </Switch>
        </div>
        // <Main moduleInfo={moduleInfo} />
    )
}

export default App;